package struts.core;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

public class StrutsConfig {
	
	
	public static Map<String, StrutsXmlBean> readXml(String classPath) throws JDOMException{
		
		SAXBuilder builder=new SAXBuilder();
		
		Document documet=builder.build(new File(classPath));
		
		Element root=documet.getRootElement();
		
		Element actionMapping=root.getChild("action-mapping");
		
		List<Element> mapping=actionMapping.getChildren();
		
		Map<String, StrutsXmlBean> xmlMap=new HashMap<String, StrutsXmlBean>();
		
		for (Element e: mapping) {
			StrutsXmlBean bean=new StrutsXmlBean();
			String path=e.getAttributeValue("path");
			bean.setActionPath(path);
			
			String type=e.getAttributeValue("type");
			bean.setActionType(type);
			
			String name=e.getAttributeValue("name");
			bean.setActionName(name);
			
			Element formBeans=root.getChild("form-beans");
			List<Element> beans=formBeans.getChildren();
			for (Element ex: beans) {
				if(name.equals(ex.getAttributeValue("name"))){
					String beanClass=ex.getAttributeValue("class");
					bean.setFormClass(beanClass);
					break;
				}
				
			}
			
			Map<String, String> map=new HashMap<String, String>();
			List<Element> forward=e.getChildren();
			for (Element x: forward) {
				map.put(x.getAttributeValue("name"), x.getAttributeValue("value"));
			}
			
			bean.setMap(map);
			
			xmlMap.put(path, bean);
		}
		
		return xmlMap;
		
	}
	
	public static void main(String[] args) throws JDOMException {
//		StrutsConfig.readXml();
	}

}
